<template>
  <div>
    <n-modal
      v-model:show="showLogin"
      preset="dialog"
      class="rounded-[24px]"
      title=""
      :closable="closable"
      :show-icon="false"
      :close-on-esc="closable"
      :mask-closable="closable"
    >
      <div>
        <div class="text-[32px] mb-[16px] font-[500] text-center">
          {{ $t("login.login") }}
        </div>
        <div>
          <n-form ref="formLoginRef" :model="loginForm" :rules="rules">
            <n-form-item path="account" :label="$t('login.inputAccount')">
              <n-input
                v-model:value="loginForm.account"
                :placeholder="$t('login.inputAccount')"
              />
            </n-form-item>
            <n-form-item path="password" :label="$t('login.inputPassword')">
              <n-input
                v-model:value="loginForm.password"
                type="password"
                :placeholder="$t('login.inputPassword')"
              />
            </n-form-item>
            <div>
              {{ $t("login.noAccount") }}?
              <span
                class="text-[--sub-color] cursor-pointer"
                @click="
                  () => {
                    showLogin = false;
                    showRegister = true;
                  }
                "
              >
                {{ $t("login.register") }}
              </span>
            </div>
            <div class="my-[16px]">
              <n-button block type="primary" @click="onClickLogin">
                {{ $t("login.login") }}
              </n-button>
            </div>
            <n-divider> Or </n-divider>
            <div class="facebook-wrapper">
              <n-icon>
                <LogoFacebook @click="onClickFacebookLogin"></LogoFacebook>
              </n-icon>
            </div>
          </n-form>
        </div>
      </div>
    </n-modal>

    <n-modal
      v-model:show="showRegister"
      preset="dialog"
      class="rounded-[24px]"
      title=""
      :closable="closable"
      :show-icon="false"
      :close-on-esc="closable"
      :mask-closable="closable"
    >
      <div>
        <div class="text-[32px] mb-[16px] font-[500] text-center">
          {{ $t("login.register") }}
        </div>
        <div>
          <n-form ref="formRegisterRef" :model="regForm" :rules="rules">
            <n-form-item path="account" :label="$t('login.inputAccount')">
              <n-input
                v-model:value="regForm.account"
                :placeholder="$t('login.inputAccount')"
              />
            </n-form-item>
            <n-form-item path="password" :label="$t('login.inputPassword')">
              <n-input
                v-model:value="regForm.password"
                type="password"
                :placeholder="$t('login.inputPassword')"
              />
            </n-form-item>
            <n-form-item
              ref="rPasswordFormItemRef"
              first
              path="confirmPassword"
              :label="$t('login.inputConfirmPassword')"
            >
              <n-input
                v-model:value="regForm.confirmPassword"
                :disabled="!regForm.password"
                type="password"
                :placeholder="$t('login.inputConfirmPassword')"
              />
            </n-form-item>

            <div>
              {{ $t("login.hasAccount") }}?
              <span
                @click="
                  () => {
                    showRegister = false;
                    showLogin = true;
                  }
                "
                class="text-[--sub-color] cursor-pointer"
              >
                {{ $t("login.login") }}
              </span>
            </div>
            <div class="my-[16px]">
              <n-button block type="primary" @click="onClickRegister">
                {{ $t("login.register") }}
              </n-button>
            </div>
            <n-divider> Or </n-divider>
            <div class="facebook-wrapper">
              <n-icon>
                <LogoFacebook @click="onClickFacebookLogin"></LogoFacebook>
              </n-icon>
            </div>
          </n-form>
        </div>
      </div>
    </n-modal>
  </div>
</template>

<script setup>
import { ref } from "vue";
import { register } from "@/api/common";
import { useMessage } from "naive-ui";
import { useUser } from "@/stores/user";
import { useI18n } from "vue-i18n";
import { LogoFacebook } from "@vicons/ionicons5";
import { Session } from "@/utils/storage";
import { useRouter } from "vue-router";
const { t } = useI18n();
const router = useRouter();
const message = useMessage();
const showLogin = ref(false);
const showRegister = ref(false);
const closable = ref(true);
const formRegisterRef = ref(null);
const formLoginRef = ref(null);
const regForm = ref({
  account: "",
  name: "",
  password: "",
  confirmPassword: "",
});
const loginForm = ref({
  account: "",
  password: "",
});
const showLoginDialog = (_closable) => {
  closable.value = _closable;
  showRegister.value = false;
  showLogin.value = true;
};
const showRegisterDialog = (_closable) => {
  closable.value = _closable;
  showLogin.value = false;
  showRegister.value = true;
};
const { loginHandler, facebookLoginHandler } = useUser();
const rules = {
  account: [
    {
      required: true,
      message: t("login.inputAccount"),
      trigger: ["input", "blur"],
    },
    {
      min: 6,
      message: t("login.lengthLimit"),
      trigger: ["input", "blur"],
    },
  ],
  password: [
    {
      required: true,
      message: t("login.inputPassword"),
    },
    {
      min: 6,
      message: t("login.lengthLimit"),
      trigger: ["input", "blur"],
    },
  ],
  confirmPassword: [
    {
      required: true,
      message: t("login.inputConfirmPassword"),
      trigger: ["input", "blur"],
    },
    {
      validator: validatePasswordStartWith,
      message: t("login.confirmPasswordFail"),
      trigger: "input",
    },
    {
      validator: validatePasswordSame,
      message: t("login.confirmPasswordFail"),
      trigger: ["blur", "password-input"],
    },
  ],
};

function validatePasswordSame(rule, value) {
  return value === regForm.value.password;
}

function validatePasswordStartWith(rule, value) {
  return (
    !!regForm.value.password &&
    regForm.value.password.startsWith(value) &&
    regForm.value.password.length >= value.length
  );
}

const onClickRegister = async (e) => {
  e.preventDefault();
  formRegisterRef.value?.validate(async (errors) => {
    if (!errors) {
      regForm.value.name = regForm.value.account;
      await register(regForm.value);
      message.success(t("login.registerSuccessTip"));
      showRegister.value = false;
      showLogin.value = true;
    } else {
      // console.log(errors);
      // message.error("验证失败");
    }
  });
};

const onClickLogin = async (e) => {
  e.preventDefault();
  formLoginRef.value?.validate(async (errors) => {
    if (!errors) {
      await loginHandler(loginForm.value);
      // message.success("Inicio de sesión exitoso");
      // showRegister.value = false;
      showLogin.value = false;
      let redirect_url = Session.get("redirect_url");
      if (redirect_url) {
        Session.remove("redirect_url");
        router.push(redirect_url);
      }
    } else {
      // console.log(errors);
      // message.error("验证失败");
    }
  });
};

onMounted(() => {});

const onClickFacebookLogin = () => {
  FB.login(function (response) {
    console.log("%c Line:279 🍒 登录结果", "color:#465975", response);
    if (response.status === "connected") {
      getFackbookUserInfo();
    }
  });
};

const getFackbookUserInfo = () => {
  FB.api("/me", { fields: "id,name,picture" }, async (response) => {
    console.log("%c Line:288 🌰 登录信息", "color:#7f2b82", response);
    await facebookLoginHandler({
      name: response.name,
      avatar: response.picture?.data?.url,
      account: response.id,
      // facebookToken: FB.getAuthResponse().accessToken,
    });

    showLogin.value = false;
    let redirect_url = Session.get("redirect_url");
    if (redirect_url) {
      Session.remove("redirect_url");
      router.push(redirect_url);
    }
  });
};

defineExpose({ showLoginDialog, showRegisterDialog });
</script>

<style lang="scss" scoped>
.facebook-wrapper {
  text-align: center;
  font-size: 32px;
  color: #0c82ee;
  margin-top: -20px;
}
</style>
